package api

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"goadmin/config"
	"goadmin/logs"
	"goadmin/models"
	"goadmin/service"
	"goadmin/utils"
	"goadmin/wechatMiniprogram"
	"net/http"
	"strconv"
)

type OrderController struct {
	svc *service.ProductService
	BaseController
}

func (con OrderController) OrderList(c *gin.Context) {
	// 绑定分页参数
	var pageInfo utils.PageInfo
	if err := c.ShouldBindQuery(&pageInfo); err != nil {
		con.errorMessage(c, "参数错误"+err.Error(), 201)
		return
	}

	// 绑定查询条件
	var query models.OrderQuery
	if err := c.ShouldBindQuery(&query); err != nil {
		con.errorMessage(c, "查询参数错误"+err.Error(), 201)
		return
	}
	// 调用服务层
	result, err := service.OrderList(pageInfo, query)
	if err != nil {
		con.errorMessage(c, "查询失败", 500)
		return
	}
	con.successMessage(c, "查询成功", result)
}
func (con OrderController) OrderShow(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		con.errorMessage(c, "invalid id", 500)
		return
	}
	p, err := service.OrderGet(id)
	if err != nil {
		con.errorMessage(c, "不存在的订单", 500)
		return
	}
	c.JSON(http.StatusOK, p)
}
func (con OrderController) AddOrder(c *gin.Context) {
	var req struct {
		ProductsID uint64 `binding:"required" json:"products_id" msg:"产品ID必要参数"`
		Quantity   uint64 `binding:"required" json:"quantity" msg:"购买数量必要参数"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		con.errorMessage(c, err.Error(), 201)
		return
	}
	_, product_err := service.GetProduct(req.ProductsID)
	if product_err != nil {
		con.errorMessage(c, "不存在的产品", 500)
		return
	}
	orderId, perr := service.AddOrder(req.ProductsID, req.Quantity, 1)
	if perr != nil {
		con.errorMessage(c, "创建订单失败:"+perr.Error(), 500)
		return
	}
	orderInfo, oError := service.OrderGet(orderId)
	if oError != nil {
		logs.Sugar().Infow("查询订单异常::", oError)
		con.errorMessage(c, "查询订单异常", 500)
		return
	}
	con.successMessage(c, "创建订单成功", orderInfo)

	logs.Sugar().Infow("产品信息orderId::", orderId)
	logs.Sugar().Infow("错误信息::", perr)
	return
	client := &wechatMiniprogram.PayClient{
		AppID:     config.Wechat.AppID,
		MchID:     config.Wechat.MchID,
		MchKey:    config.Wechat.MchKey,
		NotifyURL: config.Wechat.NotifyURL,
	}
	params, err := client.GetPayParameter(orderInfo.OrderNo, "o5MIL5Hj2TDhWV2Ps0zjkWHlvuFo", orderInfo.TotalAmount, "商品描述", "order")
	if err != nil {
		con.errorMessage(c, err.Error(), 500)
		return
	}
	// 直接 json 返回给前端即可
	jsonBytes, _ := json.Marshal(params)
	fmt.Println(string(jsonBytes))
	con.successMessage(c, "创建订单成功", string(jsonBytes))
}
